import { Box, FormControl } from '@chakra-ui/react';
import { createSelector } from '@reduxjs/toolkit';
import { stateSelector } from 'store/store';
import { useAppDispatch, useAppSelector } from 'store/storeHooks';
import IAITextarea from 'common/components/IAITextarea';
import { setPositivePrompt } from 'features/parameters/store/generationSlice';
import { isEqual } from 'lodash-es';
import { ChangeEvent, memo, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';

const promptInputSelector = createSelector(
  [stateSelector],
  ({ generation }) => {
    return {
      prompt: generation.positivePrompt,
    };
  },
  {
    memoizeOptions: {
      resultEqualityCheck: isEqual,
    },
  }
);

/**
 * Prompt input text area.
 */
const ParamPositiveConditioning = () => {
  const dispatch = useAppDispatch();
  const { prompt } = useAppSelector(promptInputSelector);
  const promptRef = useRef<HTMLTextAreaElement>(null);
  const { t } = useTranslation();
  const handleChangePrompt = useCallback(
    (e: ChangeEvent<HTMLTextAreaElement>) => {
      dispatch(setPositivePrompt(e.target.value));
    },
    [dispatch]
  );

  return (
    <Box position="relative" w="full">
      <FormControl>
        <IAITextarea
          id="prompt"
          name="prompt"
          ref={promptRef}
          value={prompt}
          placeholder={t('parameters.positivePromptPlaceholder')}
          onChange={handleChangePrompt}
          resize="vertical"
          minH={32}
        />
      </FormControl>
    </Box>
  );
};

export default memo(ParamPositiveConditioning);
